package codingforgreat.lchot150;

public class Lc003 {
     public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode();
        ListNode head = res;
        int c = 0;
        while(l1 != null && l2 != null){
            if(l1.val + l2.val + c >= 10){
                res.val = l1.val + l2.val + c - 10;
                c = 1;
            }else{
                res.val = l1.val + l2.val + c;
                c = 0;
            }
            l1 = l1.next == null ? null : l1.next;
            l2 = l2.next == null ? null : l2.next;
            if(l1 != null || l2 != null){
                res.next = new ListNode();
                res = res.next;
            }

        }
        while(l1 != null){
            if(l1.val  + c >= 10){
                res.val = l1.val  + c - 10;
                c = 1 ;
            }else{
                res.val = l1.val  + c;
                c = 0;
            }
            l1 = l1.next == null ? null : l1.next;
            if(l1 != null){
                res.next = new ListNode();
                res = res.next;
            }
        }
        while(l2 != null){
            if(l2.val  + c >= 10){
                res.val = l2.val  + c - 10;
                c = 1;
            }else{
                res.val = l2.val  + c;
                c = 0;
            }
            l2 = l2.next == null ? null : l2.next;
            if(l2 != null){
                res.next = new ListNode();
                res = res.next;
            }
        }
        if(c == 1){
            res.next = new ListNode();
            res = res.next;
            res.val = 1;
        }
        return head;
    }
}
